<template>
  <a-card :loading="loading" :bordered="false" class="weather-card">
    <!-- 天气卡片头部 -->
    <div class="weather-header">
      <h3>{{ weatherData.city || '天气信息' }}</h3>
      <span>{{ currentDate }}</span>
    </div>
    
    <!-- 天气主要内容区域 -->
    <div class="weather-content">
      <div class="weather-main">
        <!-- 天气图标 -->
        <i v-if="weatherIconClass" :class="weatherIconClass" class="weather-icon"></i>
        <div v-else class="icon-placeholder">
          <i class="anticon anticon-question-circle"></i>
        </div>
        <!-- 温度和天气状况 -->
        <div class="weather-temp">
          <span class="temp">{{ weatherData.temp }}°C</span>
          <span class="text">{{ weatherData.text }}</span>
        </div>
      </div>
      
      <!-- 天气详情 -->
      <div class="weather-details">
        <div class="detail-item">
          <span>湿度</span>
          <span>{{ weatherData.humidity }}%</span>
        </div>
        <div class="detail-item">
          <span>风力</span>
          <span>{{ weatherData.windDir }} {{ weatherData.windScale }}级</span>
        </div>
      </div>
    </div>
  </a-card>
</template>


<script>
import axios from 'axios';

export default {
  name: "WeatherCard",
  data() {
    return {
      loading: true,
      weatherData: {
        city: '',
        temp: '',
        text: '',
        humidity: '',
        windDir: '',
        windScale: '',
        icon: ''
      },
      currentDate: new Date().toLocaleDateString('zh-CN'),
      apiKey: '04ff06fa05574276bee942be44060f07'
    };
  },
  computed: {
    weatherIconClass() {
      if (!this.weatherData.icon) return '';
      const iconCode = this.weatherData.icon.replace(/[dn]$/, '');
      if (/^\d+$/.test(iconCode)) {
        return `qi-${iconCode}-fill`;
      }
      return '';
    }
  },
  methods: {
    async getLocation() {
      return new Promise((resolve, reject) => {
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(
            position => resolve(position.coords),
            error => {
              console.error('获取位置失败:', error);
              reject(error);
            }
          );
        } else {
          reject(new Error('浏览器不支持地理位置功能'));
        }
      });
    },

    async fetchWeather(lat, lon) {
      try {
        const locationRes = await axios.get(
          `https://geoapi.qweather.com/v2/city/lookup?location=${lon},${lat}&key=${this.apiKey}&lang=zh`
        );

        if (!locationRes.data.location || locationRes.data.location.length === 0) {
          throw new Error('未找到该位置的城市信息');
        }

        const locationId = locationRes.data.location[0].id;
        const weatherRes = await axios.get(
          `https://devapi.qweather.com/v7/weather/now?location=${locationId}&key=${this.apiKey}&lang=zh`
        );

        let iconCode = weatherRes.data.now.icon;
        if (!iconCode) iconCode = '100';

        this.weatherData = {
          city: locationRes.data.location[0].name,
          temp: weatherRes.data.now.temp,
          text: weatherRes.data.now.text,
          humidity: weatherRes.data.now.humidity,
          windDir: weatherRes.data.now.windDir,
          windScale: weatherRes.data.now.windScale,
          icon: iconCode
        };

      } catch (error) {
        console.error('获取天气数据失败:', error);
        this.weatherData.icon = '100';
      } finally {
        this.loading = false;
      }
    },

    loadQWeatherIcons() {
      const link = document.createElement('link');
      link.rel = 'stylesheet';
      link.href = 'https://cdn.jsdelivr.net/npm/qweather-icons@1.3.0/font/qweather-icons.css';
      document.head.appendChild(link);
    }
  },
  async created() {
    try {
      this.loadQWeatherIcons();
      const coords = await this.getLocation();
      await this.fetchWeather(coords.latitude, coords.longitude);
    } catch (error) {
      console.error('定位失败:', error);
      await this.fetchWeather(39.9042, 116.4074);
    }
  }
};
</script>

<style scoped>
.weather-card {
  border-radius: 12px;
  margin-bottom: 20px;
}

.weather-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.weather-content {
  display: flex;
  flex-direction: column;
}

.weather-main {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.weather-icon {
  font-size: 64px;
  margin-right: 16px;
  color: #1890ff;
}

.icon-placeholder {
  width: 64px;
  height: 64px;
  margin-right: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  color: #ccc;
}

.weather-temp {
  display: flex;
  flex-direction: column;
}

.temp {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 4px;
}

.text {
  font-size: 16px;
  color: #666;
}

.weather-details {
  display: flex;
  justify-content: space-between;
}

.detail-item {
  display: flex;
  flex-direction: column;
  text-align: center;
}
</style>